// 使用全局统一配置入口
const { NpmPackages } = require('../../../config/module_config.js');
const dayjs = NpmPackages.dayjs;
const { observable, action, computed, runInAction } = NpmPackages.mobx;

// 使用辅助函数
const { Helpers } = require('../../../config/module_config.js');
const { cloudHelper, pageHelper, timeHelper } = Helpers;

// 定义API路由
const API_ROUTES = {
  LIST_DOCUMENTS: 'knowledge/list_documents',
  GET_DOCUMENT: 'knowledge/get_document',
  CREATE_DOCUMENT: 'knowledge/create_document',
  UPDATE_DOCUMENT: 'knowledge/update_document',
  DELETE_DOCUMENT: 'knowledge/delete_document',
  CATEGORIES: 'knowledge/categories'
};

// 本地存储键
const STORAGE_KEYS = {
  DOCUMENTS: 'KNOWLEDGE_DOCUMENTS',
  CATEGORIES: 'KNOWLEDGE_CATEGORIES'
};

// 知识库模块Store
export const knowledgeStore = observable({
  // 所有文档列表
  documents: [],
  
  // 文档类别
  categories: [
    { id: 'all', name: '全部', icon: 'all' },
    { id: 'tech', name: '技术文档', icon: 'tech' },
    { id: 'product', name: '产品文档', icon: 'product' },
    { id: 'design', name: '设计规范', icon: 'design' },
    { id: 'api', name: 'API文档', icon: 'api' },
    { id: 'qa', name: 'Q&A', icon: 'qa' }
  ],
  
  // 当前选中的类别
  currentCategory: 'all',
  
  // 当前查看的文档
  currentDocument: null,
  
  // 搜索关键词
  searchKeyword: '',
  
  // 加载状态
  loading: false,
  
  // 是否需要刷新
  needRefresh: false,
  
  // 分页信息
  pagination: {
    page: 1,
    size: 20,
    total: 0,
    hasMore: true
  },
  
  // 排序方式
  sortOrder: {
    field: 'updateTime',
    direction: 'desc'
  },
  
  // 计算属性：筛选后的文档列表
  get filteredDocuments() {
    if (!this.documents.length) return [];
    
    // 按分类筛选
    let result = [...this.documents];
    if (this.currentCategory !== 'all') {
      result = result.filter(doc => doc.category === this.currentCategory);
    }
    
    // 按关键词搜索
    if (this.searchKeyword) {
      const keyword = this.searchKeyword.toLowerCase();
      result = result.filter(doc => 
        doc.title.toLowerCase().includes(keyword) || 
        doc.description.toLowerCase().includes(keyword)
      );
    }
    
    // 应用排序
    result.sort((a, b) => {
      if (this.sortOrder.field === 'updateTime') {
        const dateA = dayjs(a.updateTime);
        const dateB = dayjs(b.updateTime);
        return this.sortOrder.direction === 'desc' ? 
               dateB.valueOf() - dateA.valueOf() : 
               dateA.valueOf() - dateB.valueOf();
      } else if (this.sortOrder.field === 'views') {
        return this.sortOrder.direction === 'desc' ? b.views - a.views : a.views - b.views;
      } else if (this.sortOrder.field === 'likes') {
        return this.sortOrder.direction === 'desc' ? b.likes - a.likes : a.likes - b.likes;
      }
      
      return 0;
    });
    
    return result;
  },
  
  // 计算属性：搜索结果
  get searchResult() {
    if (!this.searchKeyword) return this.filteredDocuments;
    
    const keyword = this.searchKeyword.toLowerCase();
    return this.documents.filter(doc => 
      doc.title.toLowerCase().includes(keyword) || 
      doc.description.toLowerCase().includes(keyword)
    );
  },
  
  // 计算属性：各类别文档数量
  get categoryCounts() {
    const counts = { all: this.documents.length };
    
    this.categories.forEach(category => {
      if (category.id !== 'all') {
        counts[category.id] = this.documents.filter(doc => 
          doc.category === category.id
        ).length;
      }
    });
    
    return counts;
  },
  
  // 计算属性：热门文档
  get popularDocuments() {
    return [...this.documents]
      .sort((a, b) => b.views - a.views)
      .slice(0, 5);
  },
  
  // 计算属性：最近更新文档
  get recentDocuments() {
    return [...this.documents]
      .sort((a, b) => dayjs(b.updateTime).valueOf() - dayjs(a.updateTime).valueOf())
      .slice(0, 5);
  },
  
  // 加载所有文档
  loadDocuments: action(async function() {
    try {
      runInAction(() => {
        this.loading = true;
      });
      
      // 尝试从本地存储加载
      const cachedDocuments = wx.getStorageSync(STORAGE_KEYS.DOCUMENTS);
      if (cachedDocuments && cachedDocuments.length > 0 && !this.needRefresh) {
        runInAction(() => {
          this.documents = cachedDocuments;
          this.loading = false;
          
          // 重置刷新标志
          this.needRefresh = false;
        });
        
        console.log('从本地存储加载知识库文档', this.documents.length);
        return;
      }
      
      // TODO: 从服务器API加载文档
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟数据
      const documents = [
        {
          id: 1,
          title: '用户认证系统设计文档',
          category: 'tech',
          categoryText: '技术文档',
          description: '详细描述了基于JWT的用户认证系统设计，包括数据库设计、API接口设计、安全性考虑等内容。',
          author: {
            name: '张工',
            avatar: '/projects/oa/images/tabbar/my.png'
          },
          updateTime: '2024-03-10',
          views: 156,
          likes: 23,
          status: 'completed'
        },
        {
          id: 2,
          title: '智能家居产品需求文档',
          category: 'product',
          categoryText: '产品文档',
          description: '智能家居控制系统的产品需求文档，包含功能规划、用户场景、交互流程等内容。',
          author: {
            name: '李工',
            avatar: '/projects/oa/images/tabbar/my.png'
          },
          updateTime: '2024-03-09',
          views: 89,
          likes: 12,
          status: 'draft'
        },
        {
          id: 3,
          title: '移动端UI设计规范V2.0',
          category: 'design',
          categoryText: '设计规范',
          description: '移动端应用的UI设计规范，包括色彩系统、字体规范、组件设计等内容。',
          author: {
            name: '王工',
            avatar: '/projects/oa/images/tabbar/my.png'
          },
          updateTime: '2024-03-08',
          views: 234,
          likes: 45,
          status: 'draft'
        },
        {
          id: 4,
          title: 'RESTful API接口文档',
          category: 'api',
          categoryText: 'API文档',
          description: '系统RESTful API接口文档，包含接口定义、请求参数、响应格式等内容。',
          author: {
            name: '赵工',
            avatar: '/projects/oa/images/tabbar/my.png'
          },
          updateTime: '2024-03-07',
          views: 167,
          likes: 18,
          status: 'assigned',
          assignee: '陈工'
        },
        {
          id: 5,
          title: '如何解决蓝牙连接稳定性问题？',
          category: 'qa',
          categoryText: 'Q&A',
          description: '详细介绍了在智能硬件产品中常见的蓝牙连接稳定性问题及解决方案。',
          author: {
            name: '李工',
            avatar: '/projects/oa/images/tabbar/my.png'
          },
          updateTime: '2024-03-06',
          views: 321,
          likes: 56,
          status: 'assigned',
          assignee: '张工'
        }
      ];
      
      // 更新本地状态
      runInAction(() => {
        this.documents = documents;
        
        // 重置刷新标志
        this.needRefresh = false;
      });
      
      // 保存到本地存储
      wx.setStorageSync(STORAGE_KEYS.DOCUMENTS, documents);
      
      console.log('已加载文档', this.documents.length);
    } catch (error) {
      console.error('加载知识库文档失败', error);
      pageHelper.showNoneToast('加载文档失败', 2000);
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 设置当前分类
  setCurrentCategory: action(function(category) {
    this.currentCategory = category;
  }),
  
  // 按分类筛选
  filterByCategory: action(function(category) {
    this.currentCategory = category;
    // filteredDocuments是计算属性，会自动更新
  }),
  
  // 搜索文档
  search: action(function(keyword) {
    this.searchKeyword = keyword;
    // searchResult是计算属性，会自动更新
  }),
  
  // 获取单个文档
  getDocument: action(async function(id) {
    try {
      runInAction(() => {
        this.loading = true;
      });
      
      // 先从本地找
      const doc = this.documents.find(d => d.id == id);
      if (doc) {
        runInAction(() => {
          this.currentDocument = doc;
          this.loading = false;
        });
        return doc;
      }
      
      // TODO: 从服务器API获取文档
      // 暂时返回null
      runInAction(() => {
        this.currentDocument = null;
      });
      return null;
    } catch (error) {
      console.error('获取文档详情失败', error);
      pageHelper.showNoneToast('获取文档详情失败', 2000);
      return null;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 创建新文档
  createNewDocument: action(function() {
    wx.navigateTo({
      url: '/projects/oa/pages/knowledge/edit/knowledge_edit'
    , timeout: 10000, fail: function(err) {
        // 处理超时错误
        if (err.errMsg && err.errMsg.includes("timeout")) {
          wx.showToast({
            title: "页面加载超时，请重试",
            icon: "none"
          });
          return;
        }
        
        // 处理其他错误
        console.error("页面跳转失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }});
  }),
  
  // 导航到文档详情
  navigateToDocument: action(function(id) {
    wx.navigateTo({
      url: `/projects/oa/pages/knowledge/detail/knowledge_detail?id=${id}`
    });
  }),
  
  // 保存文档
  saveDocument: action(async function(document) {
    try {
      runInAction(() => {
        this.loading = true;
      });
      
      // 如果有ID则更新，否则新建
      if (document.id) {
        // 更新现有文档
        const index = this.documents.findIndex(d => d.id == document.id);
        if (index >= 0) {
          runInAction(() => {
            this.documents[index] = {
              ...this.documents[index],
              ...document,
              updateTime: timeHelper.format(dayjs(), 'YYYY-MM-DD')
            };
          });
        }
      } else {
        // 创建新文档
        const newId = Math.max(0, ...this.documents.map(d => d.id)) + 1;
        const newDoc = {
          ...document,
          id: newId,
          updateTime: timeHelper.format(dayjs(), 'YYYY-MM-DD'),
          views: 0,
          likes: 0
        };
        runInAction(() => {
          this.documents.unshift(newDoc);
        });
      }
      
      // 保存到本地存储
      wx.setStorageSync(STORAGE_KEYS.DOCUMENTS, this.documents);
      
      // 设置需要刷新标志
      runInAction(() => {
        this.needRefresh = true;
      });
      
      return true;
    } catch (error) {
      console.error('保存文档失败', error);
      pageHelper.showNoneToast('保存文档失败', 2000);
      return false;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 删除文档
  deleteDocument: action(async function(id) {
    try {
      runInAction(() => {
        this.loading = true;
      });
      
      // 从本地移除
      runInAction(() => {
        this.documents = this.documents.filter(d => d.id != id);
      });
      
      // 更新存储
      wx.setStorageSync(STORAGE_KEYS.DOCUMENTS, this.documents);
      
      // 设置需要刷新标志
      runInAction(() => {
        this.needRefresh = true;
      });
      
      return true;
    } catch (error) {
      console.error('删除文档失败', error);
      pageHelper.showNoneToast('删除文档失败', 2000);
      return false;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 修改排序方式
  setSortOrder: action(function(field, direction) {
    this.sortOrder = {
      field,
      direction
    };
  }),
  
  // 增加文档浏览量
  increaseViews: action(function(id) {
    const doc = this.documents.find(d => d.id == id);
    if (doc) {
      runInAction(() => {
        doc.views++;
      });
      
      // 更新存储
      wx.setStorageSync(STORAGE_KEYS.DOCUMENTS, this.documents);
    }
  }),
  
  // 标记/取消标记文档点赞
  toggleLike: action(function(id) {
    const doc = this.documents.find(d => d.id == id);
    if (doc) {
      // 这里简化处理，实际应该检查用户是否已点赞
      runInAction(() => {
        doc.likes++;
      });
      
      // 更新存储
      wx.setStorageSync(STORAGE_KEYS.DOCUMENTS, this.documents);
    }
  }),
  
  // 初始化知识库数据
  initKnowledgeStore: action(async function() {
    await this.loadDocuments();
  })
}); 